import threading
import utils
import re
import time
import os
from email.utils import formatdate
from tasks import get_music_size
from login import use_default_login
import tasks
import requests
from urllib3.exceptions import InsecureRequestWarning

# 禁用安全请求警告
requests.urllib3.disable_warnings(InsecureRequestWarning)


class WeChatInfrastructureEditor(utils.WeChatClient):

    def setting_page_url(self):
        return '{}/cgi-bin/settingpage?t=setting/index&action=index&token={}&lang=zh_CN'.format(self.url, self.token)

    def check_resp(self, ret, action):
        if ret['base_resp']['ret'] == 0:
            self.log_line(action + '成功')
            return True
        else:
            self.log_err('错误：' + ret['base_resp']['err_msg'])
            return False

    def up_audio_frequency(self, audio_name, audio_frequency, cookies):
        r = requests.session()
        try:
            if audio_name:
                refer_url = self.setting_page_url()
                resp = self.session.get(refer_url, verify=False).content.decode('utf-8')
                ticket_id = re.search('user_name:"([^"]+)",', resp, re.MULTILINE).group(1)
                ticket = re.search('ticket:"([^"]+)",', resp, re.MULTILINE).group(1)
                file = {'file': open(audio_name, 'rb')}
                up = r.post(
                    '{0}/cgi-bin/filetransfer?action=bizmedia&ticket_id={1}&ticket={2}&svr_time={3}&token={4}'
                    '&lang=zh_CN&seq=1'.format(self.url, ticket_id, ticket, int(time.time()), self.token),
                    {"id": "WU_FILE_0", "name": os.path.basename(audio_name), "type": "audio/mp3",
                    "lastModifiedDate": formatdate(localtime=True), "size": get_music_size(audio_name)}, files=file,
                    headers={
                        "Accept-Encoding": "gzip, deflate, br",
                        "Accept-Language": "zh-CN,zh;q=0.9",
                        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36",
                        "Referer": "https://mp.weixin.qq.com/cgi-bin/filepage?type=3&begin=0&count=21&t=media/list&token={0}&lang=zh_CN".format(
                            self.token),
                        "Origin": "https://mp.weixin.qq.com",
                        "Host": "mp.weixin.qq.com"
                    }, cookies=cookies, verify=False
                )
                print(self.gh_id,"音频开始上传...")
                try:
                    data = up.json()
                    if data['base_resp']['ret'] == 0:
                        tmpencodeid = data['content']
                        update = r.post(
                            '{0}/cgi-bin/operate_voice?oper=create'.format(self.url),
                            {
                                "tmpencodeid": tmpencodeid,
                                "category": "12",
                                "title": audio_frequency,
                                "token": self.token,
                                "lang": "zh_CN",
                                "f": "json",
                                "ajax": "1"
                            },
                            headers={
                                "Host": "mp.weixin.qq.com",
                                "Connection": "keep-alive",
                                "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36",
                                "X-Requested-With": "XMLHttpRequest",
                                "Accept": "*/*",
                                "Referer": "https://mp.weixin.qq.com/cgi-bin/filepage?type=3&begin=0&count=21&t=media/list&token={0}&lang=zh_CN".format(
                                    self.token),
                                "Accept-Encoding": "gzip, deflate, br",
                                "Accept-Language": "zh-CN,zh;q=0.9",
                                "Content-Length": "138",
                                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                                "Origin": "https://mp.weixin.qq.com"
                            }, cookies=cookies, verify=False
                        )
                        try:
                            info = update.json()
                            if info['base_resp']['ret'] == 0:
                                mation = str(info["encode_file_id"]).replace('=', '%3D')
                                print(self.gh_id, "音频上传 转码中...")
                                while True:
                                    Up = r.get(
                                        '{0}/cgi-bin/operate_voice?oper=voice_get&fileid={1}&token={2}&lang=zh_CN&f=json&ajax=1'.format(
                                            self.url, mation, self.token),
                                        headers={
                                            "Accept": "*/*",
                                            "Referer": "https://mp.weixin.qq.com/cgi-bin/filepage?type=3&begin=0&count=21&t=media/list&token={0}&lang=zh_CN".format(
                                                self.token),
                                            "Accept-Encoding": "gzip, deflate, br",
                                            "Accept-Language": "zh-CN,zh;q=0.9",
                                            "Connection": "keep-alive",
                                            "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36",
                                            "X-Requested-With": "XMLHttpRequest",
                                        }, cookies=cookies, verify=False
                                    )
                                    infos = Up.json()
                                    if infos["play_length"] == 0:
                                        continue
                                    else:
                                        self.log_line('上传音频 成功')
                                        break
                        except:
                            self.log_err('音频上传转码中 出现错误: ' + data['base_resp']['err_msg'])
                            return False
                        return True
                    else:
                        self.log_err('音频开始上传 出现错误: ' + data['base_resp']['err_msg'])
                        return False
                except:
                    print(resp.content)
                self.log_err('上传音频功能设置失败')
                return False
        except:
            self.log_err('未获取到 ticket_id，ticket，file，或获取请求的接口出现问题')
            return False


class EditorThread(threading.Thread):
    def __init__(self, service, task):
        threading.Thread.__init__(self)
        self.service = service
        self.task = task

    def run(self):
        c = WeChatInfrastructureEditor(srv)
        try:
            cookies = c.enter(self.task['gh_id'])
            if not cookies:
                return
            c.up_audio_frequency(self.task['audio_name'], self.task['audio_frequency'], cookies)
        except ConnectionError:
            pass


if __name__ == '__main__':
    m = tasks.default_manager()
    srv = use_default_login()
    chunks = m.get_task_chunks(5)
    total_chunks = len(chunks)
    current_chunk = 1
    for chunk in chunks:
        print('=第{}批线程开始='.format(current_chunk))
        pool = []
        for task_item in chunk:
            thread = EditorThread(srv, task_item)
            thread.start()
            pool.append(thread)
        for thread in pool:
            thread.join()
        print('=第{}/{}批线程结束='.format(current_chunk, total_chunks))
        current_chunk += 1
    input('运行完毕，然回车键退出')
